from django.contrib import admin
from .models import ScenicCategory, SentimentTag, TouristAttraction, SentimentComment


@admin.register(ScenicCategory)
class ScenicCategoryAdmin(admin.ModelAdmin):
    """景点分类管理"""
    list_display = ['id', 'name', 'parent', 'created_at', 'updated_at']
    list_display_links = ['id', 'name']
    list_filter = ['parent', 'created_at', 'updated_at']
    search_fields = ['name', 'description']
    list_per_page = 20
    ordering = ['-created_at']
    list_select_related = ['parent']

    # 用于在admin中显示层级结构
    def get_queryset(self, request):
        return super().get_queryset(request).prefetch_related('children')


@admin.register(SentimentTag)
class SentimentTagAdmin(admin.ModelAdmin):
    """情感标签管理"""
    list_display = ['id', 'name', 'sentiment_type', 'color', 'get_tag_count']
    list_display_links = ['id', 'name']
    list_filter = ['sentiment_type']
    search_fields = ['name']
    list_per_page = 20
    ordering = ['sentiment_type', 'name']

    def get_tag_count(self, obj):
        """显示该标签被使用的次数"""
        return obj.touristattraction_set.count()

    get_tag_count.short_description = '使用次数'


@admin.register(TouristAttraction)
class TouristAttractionAdmin(admin.ModelAdmin):
    """旅游景点管理"""
    list_display = [
        'id', 'name', 'city', 'heat_index', 'avg_sentiment_score',
        'review_count', 'status', 'created_at'
    ]
    list_display_links = ['id', 'name']
    list_filter = ['status', 'city', 'province', 'created_at', 'categories']
    search_fields = ['name', 'location', 'city', 'description']
    list_per_page = 20
    ordering = ['-heat_index', '-created_at']

    # 在编辑页面显示多对多字段
    filter_horizontal = ['categories', 'sentiment_tags']

    # 只读字段
    readonly_fields = [
        'heat_index', 'avg_sentiment_score', 'review_count',
        'positive_count', 'neutral_count', 'negative_count',
        'created_at', 'updated_at'
    ]

    # 字段集分组
    fieldsets = (
        ('基础信息', {
            'fields': ('name', 'description', 'location', 'city', 'province')
        }),
        ('媒体信息', {
            'fields': ('main_image', 'gallery_images')
        }),
        ('分类标签', {
            'fields': ('categories', 'sentiment_tags')
        }),
        ('舆情分析', {
            'fields': (
                'avg_sentiment_score', 'heat_index', 'review_count',
                'positive_count', 'neutral_count', 'negative_count'
            ),
            'classes': ('collapse',)  # 可折叠
        }),
        ('状态管理', {
            'fields': ('status', 'created_by')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )

    # 自动设置创建者
    def save_model(self, request, obj, form, change):
        if not obj.pk:  # 新建时设置创建者
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

    # 自定义动作
    actions = ['make_published', 'make_draft', 'update_sentiment_stats']

    def make_published(self, request, queryset):
        """批量发布景点"""
        updated = queryset.update(status='published')
        self.message_user(request, f'{updated} 个景点已发布')

    make_published.short_description = "发布选中的景点"

    def make_draft(self, request, queryset):
        """批量设为草稿"""
        updated = queryset.update(status='draft')
        self.message_user(request, f'{updated} 个景点已设为草稿')

    make_draft.short_description = "将选中的景点设为草稿"

    def update_sentiment_stats(self, request, queryset):
        """批量更新情感统计"""
        for attraction in queryset:
            attraction.update_sentiment_stats()
        self.message_user(request, f'{queryset.count()} 个景点的情感统计已更新')

    update_sentiment_stats.short_description = "更新选中景点的情感统计"


@admin.register(SentimentComment)
class SentimentCommentAdmin(admin.ModelAdmin):
    """情感评论管理"""
    list_display = [
        'id', 'attraction', 'author', 'sentiment_label',
        'rating', 'source_platform', 'is_active', 'commented_at'
    ]
    list_display_links = ['id', 'attraction']
    list_filter = [
        'sentiment_label', 'source_platform', 'is_active',
        'is_auto_collected', 'commented_at', 'rating'
    ]
    search_fields = [
        'content', 'author__username', 'attraction__name'
    ]
    list_per_page = 20
    ordering = ['-commented_at']

    # 优化外键显示
    raw_id_fields = ['attraction', 'author', 'parent']
    list_select_related = ['attraction', 'author', 'parent']

    # 只读字段
    readonly_fields = [
        'sentiment_score', 'sentiment_label',
        'created_at', 'updated_at', 'commented_at'
    ]

    # 字段集分组
    fieldsets = (
        ('评论内容', {
            'fields': ('content', 'rating')
        }),
        ('关联信息', {
            'fields': ('attraction', 'author', 'parent')
        }),
        ('情感分析', {
            'fields': ('sentiment_score', 'sentiment_label'),
            'classes': ('collapse',)
        }),
        ('来源信息', {
            'fields': ('source_platform', 'is_auto_collected')
        }),
        ('状态管理', {
            'fields': ('is_active',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at', 'commented_at'),
            'classes': ('collapse',)
        }),
    )

    # 自定义动作
    actions = ['activate_comments', 'deactivate_comments', 'analyze_sentiment']

    def activate_comments(self, request, queryset):
        """批量激活评论"""
        updated = queryset.update(is_active=True)
        self.message_user(request, f'{updated} 条评论已激活')

    activate_comments.short_description = "激活选中的评论"

    def deactivate_comments(self, request, queryset):
        """批量禁用评论"""
        updated = queryset.update(is_active=False)
        self.message_user(request, f'{updated} 条评论已禁用')

    deactivate_comments.short_description = "禁用选中的评论"

    def analyze_sentiment(self, request, queryset):
        """批量重新分析情感"""
        for comment in queryset:
            comment.analyze_sentiment()
            comment.save()
        self.message_user(request, f'{queryset.count()} 条评论的情感分析已更新')

    analyze_sentiment.short_description = "重新分析选中评论的情感"


# 可选：添加管理站点标题
admin.site.site_header = '旅游景点舆情监测系统管理后台'
admin.site.site_title = '舆情监测系统'
admin.site.index_title = '系统管理'